const { rotateCanvas } = require("../../../utils/utils")

let lastX = 0 // 笔接触签名容器的实时位置
let lastY = 0 // 笔接触签名容器的实时位置
let context = null // canvas绘图上下文
let canvas = null // canvas对象
let isDrawing = false // 是否正在签名

const componentOptions = {
	// 组件选项
	options: {
		multipleSlots: true,
	},
	behaviors: [],
	// 组件数据
	data: {
		isPageHidden: false, // 页面是否处于隐藏状态
		innerWidth: 0, // 屏幕宽度
		innerHeight: 0, // 屏幕高度
		show: false,
	},
	// 数据监听器
	observers: {},
	// 组件方法
	methods: {
		init() {
			// 获取屏幕宽高
			const { windowWidth, windowHeight } = wx.getSystemInfoSync()
			this.setData({
				innerWidth: windowWidth,
				innerHeight: windowHeight - 100,
			})
		},
		showCanvas() {
			this.setData({
				show: true,
			})
			this.initCanvas()
		},
		hideCanvas() {
			this.setData({
				show: false,
			})
		},
		//初始化签名画布
		initCanvas() {
			//初始化签名面板canvas容器
			const query = wx.createSelectorQuery()
			query
				.in(this)
				.select("#signature-pad")
				.fields(
					{
						size: true,
						node: true,
					},
					(res) => {
						canvas = res.node
						canvas.width = this.data.innerWidth
						canvas.height = this.data.innerHeight
						context = canvas.getContext("2d")
						//绘制一个白色的背景
						context.fillStyle = "white"
						context.fillRect(0, 0, canvas.width, canvas.height)
					},
				)
				.exec()
		},
		// canvas 绑定事件
		// 记录笔开始的位置
		handleTouchstart(e) {
			isDrawing = true
			lastX = e.touches[0].clientX
			lastY = e.touches[0].clientY
		},
		//记录笔迹移动的轨迹
		handleTouchMove(e) {
			if (isDrawing) {
				//绘制很多条微小的线段
				context.beginPath()
				context.moveTo(lastX, lastY)
				context.lineTo(e.touches[0].clientX, e.touches[0].clientY)
				//设置笔记的粗细
				context.lineWidth = 5
				context.stroke()
				//记住笔的最后位置，以便下次的绘制周期使用
				lastX = e.touches[0].clientX
				lastY = e.touches[0].clientY
			}
		},
		//抬笔
		handleTouchEnd(e) {
			isDrawing = false
		},
		//清除画布
		handleClearCanvas() {
			context.clearRect(0, 0, canvas.width, canvas.height)
			context.fillStyle = "white"
			context.fillRect(0, 0, canvas.width, canvas.height)
		},
		//提交
		submit() {
			//旋转图片
			wx.createSelectorQuery()
				.in(this)
				.select("#_canvas")
				.fields({ node: true }, (res) => {
					const _canvas = res.node
					rotateCanvas(canvas, "right", _canvas).then((res) => {
						//转为base64
						const base64 = res.toDataURL("image/jpeg")
						this.triggerEvent("submit", base64)
						this.hideCanvas()
					})
				})
				.exec()
		},
	},
	// 组件生命周期
	lifetimes: {
		created() {},
		attached() {},
		ready() {
			this.init()
		},
		moved() {},
		detached() {},
	},
	definitionFilter() {},
	// 页面生命周期
	pageLifetimes: {
		// 页面被展示
		show() {},
		// 页面被隐藏
		hide() {
			this.setData({
				isPageHidden: true,
			})

			// 清除定时器等操作
		},
		// 页面尺寸变化时
		resize() {},
	},
}

Component(componentOptions)
